﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.IO;

namespace BIZ.Common
{
    /// <summary>
    /// 客户端文件上传实现
    /// </summary>
    public class UploadService
    {
        //URL发布路径
        private string publicPath;
        //本地存储路径
        private string storagePath;
        //指示是否实际上传了一个文件
        private bool _uploaded = false;

        /// <summary>
        /// 构造一个处理客户端上传的文件的对象
        /// </summary>
        /// <param name="pathend">用于在默认文件保存路径后附加一个子目录名</param>
        public UploadService()
        {
            var uploadPath = HostingEnvironment.IsHosted
                                ? HostingEnvironment.MapPath("~/Upload/") ?? ""
                                : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Upload");

            storagePath = Path.Combine(uploadPath,
                                        DateTime.Now.Year.ToString(),
                                        DateTime.Now.Month.ToString()
                                       );

            var appPath = "";
            if (HostingEnvironment.IsHosted)
            {
                appPath = HostingEnvironment.ApplicationVirtualPath;
            }
            if (!appPath.EndsWith("/"))
                appPath = appPath + '/';
            if (!appPath.StartsWith("/"))
                appPath = '/' + appPath;

            publicPath = appPath + "Upload/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/";
        }

        /// <summary>
        /// 保存客户端上传文件
        /// </summary>
        public string Save(HttpPostedFileBase file, bool VerifyExt = true /* 检查文件扩展名 */)
        {
            var ext = Path.GetExtension(file.FileName).ToLower();
            var fn = DateTime.Now.ToString("yyyyMMddHHmmss") + ext;
            var thispath = Path.Combine(storagePath, fn);
            string[] AllowExts = { ".jpg", ".jpeg", ".rar", ".bmp", ".png", ".doc", ".xls", ".txt", ".rtf", ".swf", ".zip", ".pptx", ".docx" };
            //判断扩展名是否符合要求
            if (!string.IsNullOrEmpty(ext) && !AllowExts.Contains(ext) && VerifyExt)
            {
                throw new Exception(String.Format("不允许上传({0})类型的文件。", ext));
            }

            if (File.Exists(thispath))
            {
                _uploaded = false;
                return publicPath + fn;
            }

            CreatFolderIfNotExists(storagePath);

            file.SaveAs(thispath);

            _uploaded = true;
            return publicPath + fn;
        }

        public void CreatFolderIfNotExists(string path)
        {
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
        }
        /// <summary>
        /// 是否有新的上传文件
        /// </summary>
        public bool Uploaded { get { return _uploaded; } }
    }
}